import React, { useState, useEffect, useRef, useCallback } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Button,
  Row,
  Col,
  Space,
  Form,
  Checkbox,
  message,
  Tabs,
  Select,
  DatePicker,
  Input,
  Radio,
  InputNumber,
  Table,
  Menu,
  Dropdown,
  Modal,
  Badge,
  Tag,
  Drawer,
} from 'antd';
import {
  PlusOutlined,
  PrinterOutlined,
  SyncOutlined,
  DownOutlined,
  RightOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
  BulbOutlined,
  SaveOutlined,
} from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import moment from 'moment';
import CateSelect from '@/components/CategoryComponent';
import { VendorSelect, EmpSelect } from '@/components/FormItemSelect';
import TempletePO from '../PrintTemplete/TempletePO';
import request from '@/utils/request';
import PrintModal from '@/components/PrintModal';
import SuggComp from './components/suggComp';
import QuickMenu from '@/components/QuickMenu';
import QuerySelect from '@/components/QuerySelect';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/POHeader/';
const apiURLPODetail = '/api/services/app/PODetail/';
const apiURLPORel = '/api/services/app/PORel/';
const apiURLVendor = '/api/services/app/Vendor/';
const apiURLVendorPart = '/api/services/app/VendPart/';

const ViewPage: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState<any>({ poNum: 0 });
  const [poDetail, setPoDetail] = useState({ poLine: 0 });
  const [poRel, setPoRel] = useState({});
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [dataSource2, setDataSource2] = useState([]);
  const [defTab, setDefTab] = useState('1');
  const [poErr, setPoErr] = useState(0);
  const [poDtlErr, setPoDtlErr] = useState(0);
  const [poRelErr, setPoRelErr] = useState(0);
  const [visible2, setVisible2] = useState(false);
  const [partNum, setPartNum] = useState('');
  const [partRevs, setPartRevs] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [selectedRowKeys2, setSelectedRowKeys2] = useState<any[]>([]);
  const [tranType, setTranType] = useState('');
  const [vendor, setVendor] = useState({});
  const [terms, setTerms] = useState({});
  const [taxRegionCode, setTaxRegionCode] = useState('');
  const [vendorNum, setVendorNum] = useState('');
  const [visible3, setVisible3] = useState(false);
  const intl = useIntl();
  const printArea = useRef<any>(null);
  const formRef = useRef<any>(null);

  useEffect(() => {
    // componentDidMount logic
  }, []);

  const onFinishFailed = (errorInfo: any) => {
    let poErr = 0;
    let poDtlErr = 0;
    let poRelErr = 0;
    errorInfo.errorFields.forEach((element: any) => {
      if (element.name[0] == 'POHeader') {
        poErr++;
      } else if (element.name[0] == 'PODetail') {
        poDtlErr++;
      } else if (element.name[0] == 'PORel') {
        poRelErr++;
      }
      setPoErr(poErr);
      setPoDtlErr(poDtlErr);
      setPoRelErr(poRelErr);
    });
  };

  const onFinish = (values: any) => {
    if (defTab === '1' && values.POHeader) {
      values.POHeader.promiseDate = values.POHeader.promiseDate?.format('YYYY-MM-DD');
      request(apiURL + 'Update', {
        method: 'PUT',
        data: values.POHeader,
      }).then((response) => {
        if (response) {
          if (response.success) {
            message.success(intl.formatMessage({ id: 'pages.save.success' }));
            setData(response.result);
          }
          setLoading(false);
        }
      });
    }

    if (defTab === '2' && values.PODetail) {
      values.PODetail.TaxCode = values.POHeader.userChar1;
      values.PODetail.promiseDt = values.PODetail.dueDate =
        values.POHeader.promiseDate?.format('YYYY-MM-DD');
      console.log(values);

      request(apiURLPODetail + 'Modify', {
        method: 'POST',
        data: [values.PODetail],
      }).then((response) => {
        if (response) {
          if (response.success) {
            const data = response.result.data;
            const items: any = [];
            dataSource.forEach((element: any) => {
              if (element.id == data.id) {
                data.items = element.items;
                items.push(data);
              } else {
                items.push(element);
              }
            });
            setDataSource(items);
            message.success(intl.formatMessage({ id: 'pages.save.success.poline' }));
          } else {
            message.error(response.error.message);
          }
          setLoading(false);
        }
      });
    }

    if (defTab === '3' && values.PORel) {
      values.PORel.dueDate = values.PORel.dueDate?.format('YYYY-MM-DD');
      values.PORel.promiseDt = values.PORel.promiseDt?.format('YYYY-MM-DD');
      request(apiURLPORel + 'Modify', {
        method: 'POST',
        data: [values.PORel],
      }).then((response) => {
        if (response) {
          if (response.success) {
            const data = response.result.data;
            const items: any = [];
            dataSource2.forEach((element: any) => {
              if (element.id == data.id) {
                items.push(data);
              } else {
                items.push(element);
              }
            });
            setDataSource2(items);
            message.success(intl.formatMessage({ id: 'pages.save.success.porel' }));
          } else {
            message.error(response.error.message);
          }
          setLoading(false);
        }
      });
    }
    setPoErr(0);
    setPoDtlErr(0);
    setPoRelErr(0);
    //this.getPO(values.POHeader)
  };

  const setCurrentPO = (e?: any) => {
    getPO({
      poNum: e.PONum,
    });
  };

  const getPO = (e?: any) => {
    if (e.poNum) {
      setLoading(true);
      request(apiURL + 'GetByNum', {
        method: 'GET',
        params: { num: e.poNum },
      }).then((response) => {
        if (response) {
          if (response.success) {
            if (response.result.success) {
              const POHeader = response.result.data;
              if (POHeader.promiseDate) POHeader.promiseDate = moment(POHeader.promiseDate);
              setData(POHeader);
              getVendor(POHeader.vendorNum);
              formRef.current.setFieldsValue({ POHeader });
              if (POHeader.items) getPODetail(POHeader.items);
            } else {
              message.error(response.result.message);
            }
          } else {
            message.error(response.error.message);
          }
          setLoading(false);
        }
      });
    }
  };

  const getPODetail = (data: any) => {
    const dataDtl = data[0];
    if (dataDtl) {
      setDataSource(data);
      setPoDetail(dataDtl);
      setPartNum(dataDtl.partNum);
      formRef.current.setFieldsValue({ PODetail: dataDtl });
      if (dataDtl.items) getPORel(dataDtl.items);
    }
  };

  const getPORel = (data: any) => {
    const dataRel = data[0];
    setDataSource2(data);
    setPoRel(dataRel);
    if (dataRel) {
      if (dataRel.dueDate) dataRel.dueDate = moment(dataRel.dueDate);
      if (dataRel.promiseDt) dataRel.promiseDt = moment(dataRel.promiseDt);
      setTranType(dataRel.tranType);
    }
    formRef.current.setFieldsValue({ PORel: dataRel });
  };

  const newPO = () => {
    const { currentUser } = props;
    const value = {
      approvalStatus: 'U',
      poType: 'ipo',
      buyerID: '0',
      termsCode: '0',
      entryPerson: currentUser.userName,
      shipViaCode: '0',
      currencyCode: '0',
    };
    request(apiURL + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.newPo.success' }));
          const POHeader = response.result.data;
          setData(POHeader);
          formRef.current.setFieldsValue({ POHeader });
          const PODetail = {
            poNum: POHeader.poNum,
            partNum: '0',
            lineDesc: '0',
            ium: 'PCS',
            uom: '0',
            classID: '0',
            revisionNum: '0',
            unitCost: 0,
            promiseDt: moment(new Date()),
            dueDate: moment(new Date()),
          };
          formRef.current.setFieldsValue({ PODetail });
          const PORel = {
            poNum: POHeader.poNum,
            poLine: 1,
            warehouseCode: '',
            promiseDt: moment(new Date()),
            dueDate: moment(new Date()),
            tranType: 'STK',
            relQty: 1,
          };
          formRef.current.setFieldsValue({ PORel });
        } else {
          message.error(response.error.message);
        }
        setLoading(false);
      }
    });
  };

  const newPODetail = () => {
    if (data.poNum == 0) {
      message.warning(intl.formatMessage({ id: 'pages.createPOFirst' }));
      return;
    }
    const value = {
      poNum: data.poNum,
      partNum: '0',
      lineDesc: '0',
      ium: 'PCS',
      uom: '0',
      classID: '0',
      revisionNum: '0',
      promiseDt: data.promiseDate,
      dueDate: data.promiseDate,
      taxCode: taxRegionCode,
    };
    request(apiURLPODetail + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        setLoading(true);
        if (response.success) {
          const _data = response.result.data;
          formRef.current.setFieldsValue({ PODetail: _data });
          const items: any = [];
          items.push(_data);
          dataSource.forEach((element: any) => {
            items.push(element);
          });
          setPoDetail(_data);
          setDefTab('2');
          setDataSource(items);
        } else {
          message.error(response.error.message);
        }
        setLoading(false);
      }
    });
  };

  const newPORel = () => {
    if (data.poNum == 0) {
      message.warning(intl.formatMessage({ id: 'pages.createPOFirst' }));
      return;
    }
    if (poDetail.poLine == 0) {
      message.warning(intl.formatMessage({ id: 'pages.createPOLineFirst' }));
      return;
    }
    const value = {
      poNum: data.poNum,
      poLine: poDetail.poLine,
      warehouseCode: '',
      promiseDt: data.promiseDate,
      dueDate: data.promiseDate,
      tranType: 'STK',
      relQty: 1,
    };
    request(apiURLPORel + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        setLoading(true);
        if (response.success) {
          const _data = response.result.data;
          if (_data.promiseDt) _data.promiseDt = moment(_data.promiseDt);
          if (_data.dueDate) _data.dueDate = moment(_data.dueDate);
          formRef.current.setFieldsValue({ PORel: _data });
          const items: any = [];
          items.push(_data);
          dataSource2.forEach((element: any) => {
            items.push(element);
          });
          setDefTab('3');
          setDataSource2(items);
        } else {
          message.error(response.error.message);
        }
        setLoading(false);
      }
    });
  };

  const setPODetail = (row: any) => {
    setPoDetail(row);
    setDefTab('2');
    formRef.current.setFieldsValue({ PODetail: row });
    getPORel(row.items);
  };

  const setPORel = (row: any) => {
    setPoRel(row);
    setDefTab('3');
    if (row.promiseDt) row.promiseDt = moment(row.promiseDt);
    if (row.dueDate) row.dueDate = moment(row.dueDate);
    formRef.current.setFieldsValue({ PORel: row });
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        if (data.items != null && data.items.length > 0) {
          message.error(intl.formatMessage({ id: 'pages.cannotdelete.existPoline' }));
          return;
        }
        request(apiURL + 'Delete', {
          method: 'DELETE',
          params: { id: data.id },
        }).then((response) => {
          if (response) {
            if (response.success) {
              formRef.current.resetFields();
            } else {
              message.error(response.error.message);
            }
          }
        });
      },
    });
  };

  const delBatchD = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(apiURLPODetail + 'DelBatch', {
          method: 'POST',
          data: selectedRowKeys,
        }).then((response) => {
          if(response && response.success){
            const lists = dataSource.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
            setDataSource(lists);
          }
        });
      },
    });
  };

  const delBatchR = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(apiURLPORel + 'DelBatch', {
          method: 'POST',
          data: selectedRowKeys2,
        }).then((response) => {
          const lists = dataSource2.filter((o: any) => selectedRowKeys2.indexOf(o.id) < 0);
          setDataSource2(lists);
        });
      },
    });
  };

  const handleMenuClick = (e: any) => {
    if (e.key === '1') {
      newPO();
      formRef.current.resetFields();
      setPoErr(0);
      setPoDtlErr(0);
      setPoRelErr(0);
      setDataSource([]);
      setDataSource2([]);
    } else if (e.key === '2') {
      newPODetail();
    } else {
      newPORel();
    }
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const setCurrent = (part?: any) => {
    if (part) {
      const PODetail: any = {};
      PODetail.partNum = part.PartNum;
      PODetail.lineDesc = part.PartDescription;
      PODetail.ium = part.IUM;
      const datas = formRef.current.getFieldsValue();
      request(apiURLVendorPart + 'GetList', {
        method: 'GET',
        params: { vendorNum: datas.POHeader.vendorNum, partNum: part.PartNum, effe: 1 },
      }).then((response) => {
        if (response && response.result) {
          const item = response.result.items[0];
          if (item) {
            PODetail.unitCost = item?.baseUnitPrice;
          } else {
            message.warning(intl.formatMessage({ id: 'pages.vendorPart.notfound' }));
          }
        } else {
          message.warning(intl.formatMessage({ id: 'pages.vendorPart.notfound' }));
        }
        formRef.current.setFieldsValue({ PODetail });
        setPartRevs(part.Revs?.split(','));
      });
    }
    setVisible2(false);
    setPartNum(part.partNum);
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const onSelectChange2 = (selectedRowKeys2: any) => {
    setSelectedRowKeys2(selectedRowKeys2);
  };

  const setOrderRelJob = (item: any) => {
    const PORel = {
      orderNum: item.OrderNum,
      orderLine: item.OrderLine,
      orderRelNum: item.OrderRelNum,
      relQty: item.OurReqQty,
      ium: item.IUM,
    };
    const PODetail = {
      partNum: item.PartNum,
      lineDesc: item.PartDescription,
      ium: item.IUM,
    };
    formRef.current.setFieldsValue({ PORel, PODetail });
  };

  const setPORelJob = (item: any) => {
    const PORel = {
      jobNum: item.JobNum,
      jobSeq: item.MtlSeq,
      assemblySeq: item.AssemblySeq,
      relQty: item.RequiredQty,
      ium: item.IUM,
    };
    const PODetail = {
      partNum: item.PartNum,
      lineDesc: item.PartDescription,
      ium: item.IUM,
    };
    formRef.current.setFieldsValue({ PORel, PODetail });
  };

  const setPORelJobOpr = (item: any) => {
    const PORel = {
      jobNum: item.JobNum,
      jobSeq: item.OprSeq,
      assemblySeq: item.AssemblySeq,
      relQty: item.RequiredQty,
      commentText: item.OpDesc + ' ' + item.CommentText,
    };
    const PODetail = {
      partNum: item.PartNum,
      lineDesc: item.PartDescription,
      revisionNum: item.RevisionNum,
      ium: item.IUM,
    };
    formRef.current.setFieldsValue({ PORel, PODetail });
  };

  const setPORelDemd = (item: any) => {
    const PORel = {
      reqNum: item.Id,
      relQty: item.ReqQty,
      ium: item.IUM,
    };
    const PODetail = {
      partNum: item.PartNum,
      lineDesc: item.PartDescription,
      ium: item.IUM,
    };
    formRef.current.setFieldsValue({ PORel, PODetail });
  };

  const sendApprv = () => {
    if (!data || !data.id) {
      message.warning(intl.formatMessage({ id: 'pages.openPOFirst' }));
      return;
    }
    request(apiURL + 'AppApprv', {
      method: 'POST',
      data: [data.id],
    }).then((response) => {
      if (response && response.success) {
        message.success(intl.formatMessage({ id: 'pages.submit.success' }));
        getPO(data);
      }
    });
  };

  const doPrint = () => {
    setVisible(true);
  };

  const getVendor = (num: any) => {
    request(apiURLVendor + 'GetByNum', {
      method: 'GET',
      params: { num },
    }).then((response) => {
      if (response && response.success) {
        const vendor = response.result.data;
        setVendor(vendor);
      }
    });
  };

  const setVendorFun = (e: any) => {
    request(apiURLVendor + 'GetByNum', {
      method: 'GET',
      params: { num: e },
    }).then((response) => {
      if (response && response.success) {
        const data = response.result.data;
        const POHeader = {
          termsCode: data.termsCode,
          currencyCode: data.currencyCode,
          userChar1: data.taxRegionCode,
        };
        setTaxRegionCode(data.taxRegionCode);
        setVendorNum(data.vendorNum);
        setVendor(data);
        formRef.current.setFieldsValue({ POHeader });
      }
    });
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.poLine" />,
      dataIndex: 'poLine',
      key: 'poLine',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.openline" />,
      dataIndex: 'openLine',
      key: 'openLine',
      width: 60,
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      key: 'partNum',
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'lineDesc',
      key: 'lineDesc',
      width: 150,
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.unitCost" />,
      dataIndex: 'unitCost',
      key: 'unitCost',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      width: 60,
      render: (record: any) =>
        dataSource.length >= 1 ? (
          <Space>
            <a onClick={() => setVisible3(true)}>
              <FormattedMessage id="pages.suggest" />
            </a>
          </Space>
        ) : null,
    },
  ];

  const columnRel = [
    {
      title: <FormattedMessage id="pages.poLine" />,
      dataIndex: 'poLine',
      key: 'poLine',
    },
    {
      title: <FormattedMessage id="pages.poRelNum" />,
      dataIndex: 'poRelNum',
      key: 'PORelNum',
    },
    {
      title: <FormattedMessage id="pages.openline" />,
      dataIndex: 'openRelease',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: <FormattedMessage id="pages.relQty" />,
      dataIndex: 'relQty',
      key: 'relQty',
    },
    {
      title: <FormattedMessage id="pages.promiseDate" />,
      dataIndex: 'promiseDt',
      key: 'promiseDt',
      render: (text: any) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
    },
    {
      title: <FormattedMessage id="pages.dueDate" />,
      dataIndex: 'dueDate',
      key: 'dueDate',
      render: (text: any) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
    },
  ];

  const selectRev = (
    <Select placeholder={<FormattedMessage id="pages.revision" />}>
      {partRevs?.map((item: any) => (
        <Select.Option key={item} value={item}>
          {item}
        </Select.Option>
      ))}
    </Select>
  );

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const rowSelection2 = {
    selectedRowKeys2,
    onChange: onSelectChange2,
  };

  const myTag = (status: string) => {
    if (status === 'A')
      return (
        <Tag color="#87d068">
          <FormattedMessage id="pages.approved" />
        </Tag>
      );
    else if (status === 'R')
      return (
        <Tag color="#f50">
          <FormattedMessage id="pages.rejected" />
        </Tag>
      );
    else if (status === 'P')
      return (
        <Tag color="#2db7f5">
          <FormattedMessage id="pages.submitted" />
        </Tag>
      );
    else
      return (
        <Tag>
          <FormattedMessage id="pages.unSubmit" />
        </Tag>
      );
  };

  const disabled =
    data.approvalStatus == 'A' || data.approvalStatus == 'P' || data == null || data.poNum == 0;

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Form {...layout} ref={formRef} onFinish={onFinish} onFinishFailed={onFinishFailed}>
        <Space style={{ marginBottom: 8 }}>
          <Dropdown
            overlay={
              <Menu onClick={handleMenuClick}>
                <Menu.Item key="1" icon={<RightOutlined />}>
                  <FormattedMessage id="pages.newPO" />
                </Menu.Item>
                <Menu.Item key="2" icon={<RightOutlined />}>
                  <FormattedMessage id="pages.newPOLine" />
                </Menu.Item>
                <Menu.Item key="3" icon={<RightOutlined />}>
                  <FormattedMessage id="pages.newPORelNum" />
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="primary" icon={<PlusOutlined />}>
              <span>
                <FormattedMessage id="pages.new" />
              </span>{' '}
              <DownOutlined />
            </Button>
          </Dropdown>
          <Button
            type="primary"
            htmlType="submit"
            disabled={disabled}
            loading={loading}
            icon={<SaveOutlined />}
          >
            <span>
              <FormattedMessage id="pages.save" />
            </span>
          </Button>
          <Button type="primary" icon={<SyncOutlined />} onClick={() => getPO(data)}>
            <span>
              <FormattedMessage id="pages.refresh" />
            </span>
          </Button>
          <Button danger icon={<CloseOutlined />} onClick={delObj} disabled={disabled}>
            <span>
              <FormattedMessage id="pages.delete" />
            </span>
          </Button>
          <Button type="ghost" icon={<PrinterOutlined />} onClick={doPrint}>
            <span>
              <FormattedMessage id="pages.print" />
            </span>
          </Button>
          <QuickMenu path="/purchase/poEntry" icon="icon-shipped" title="pages.POEntry" />
        </Space>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={24} md={24} lg={12} xl={12}>
            <Card>
              <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
                <TabPane
                  tab={
                    <Badge count={poErr}>
                      <FormattedMessage id="pages.summary" />
                    </Badge>
                  }
                  key="1"
                >
                  <Form.Item name={['POHeader', 'id']} label="ID" hidden>
                    <Input disabled />
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.poNum" />}
                    style={{ marginBottom: 0 }}
                  >
                    <Input.Group compact>
                      <Form.Item name={['POHeader', 'poNum']}>
                        <Input />
                      </Form.Item>
                      <Form.Item noStyle>
                        <QuerySelect
                          width={780}
                          sysReportName="ReportPO"
                          text={<FormattedMessage id="pages.select" />}
                          title={<FormattedMessage id="pages.poNum" />}
                          btntype="primary"
                          setCurrent={setCurrentPO}
                          scroll={{ x: 'max-content', y: '200px' }}
                          search={{
                            filterType: 'light',
                          }}
                        />
                      </Form.Item>
                      <Form.Item
                        name={['POHeader', 'approve']}
                        valuePropName="checked"
                        style={{ marginLeft: 20 }}
                      >
                        <Checkbox disabled>
                          <FormattedMessage id="pages.approved" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item>
                        <Checkbox
                          checked={data.approvalStatus == 'P'}
                          onChange={sendApprv}
                          disabled={disabled}
                        >
                          <FormattedMessage id="pages.submitApprove" />
                        </Checkbox>
                        {myTag(data.approvalStatus)}
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    name={['POHeader', 'promiseDate']}
                    label={<FormattedMessage id="pages.promiseDate" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.promiseDate.required" />,
                      },
                    ]}
                  >
                    <DatePicker />
                  </Form.Item>
                  <Form.Item
                    name={['POHeader', 'poType']}
                    label={<FormattedMessage id="pages.poType" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.poType.required" /> },
                    ]}
                  >
                    <Select style={{ width: 200 }}>
                      <Select.Option value="ipo">
                        <FormattedMessage id="pages.IPO" />
                      </Select.Option>
                      <Select.Option value="opo">
                        <FormattedMessage id="pages.OPO" />
                      </Select.Option>
                    </Select>
                  </Form.Item>
                  <EmpSelect
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.buyerID.required" /> },
                    ]}
                    tooltip={intl.formatMessage({ id: 'pages.addEmployeeInDepartment(PD)' })}
                    width={200}
                    name={['POHeader', 'buyerID']}
                    label={<FormattedMessage id="pages.buyerID" />}
                    params={{
                      deptCode: 'PD',
                    }}
                  />
                  <VendorSelect
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.vendorNum.required" />,
                      },
                    ]}
                    showSearch={true}
                    width={280}
                    name={['POHeader', 'vendorNum']}
                    label={<FormattedMessage id="pages.vendor" />}
                    setCurrent={setVendorFun}
                  />
                  <CateSelect
                    layout="Terms"
                    width={200}
                    name={['POHeader', 'termsCode']}
                    label={<FormattedMessage id="pages.termsCode" />}
                    callback={(e: any) => setTerms(e)}
                    required
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.termsCode.required" />,
                      },
                    ]}
                  />
                  <CateSelect
                    layout="ShipVia"
                    width={200}
                    name={['POHeader', 'shipViaCode']}
                    label={<FormattedMessage id="pages.shipViaCode" />}
                    required
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.shipViaCode.required" />,
                      },
                    ]}
                  />
                  <CateSelect
                    layout="currency"
                    width={200}
                    name={['POHeader', 'currencyCode']}
                    label={<FormattedMessage id="pages.currencyCode" />}
                    required
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.shipViaCode.required" />,
                      },
                    ]}
                  />
                  <Form.Item
                    name={['POHeader', 'entryPerson']}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.entryPerson.required" />,
                      },
                    ]}
                    label={<FormattedMessage id="pages.entryPerson" />}
                  >
                    <Input style={{ width: 120 }} />
                  </Form.Item>
                  <Form.Item name={['POHeader', 'userChar1']} label="userChar1" hidden>
                    <Input disabled />
                  </Form.Item>
                  <CateSelect
                    layout="Invoice.Header"
                    width={240}
                    name={['POHeader', 'userChar2']}
                    label={<FormattedMessage id="pages.Invoice.Header" />}
                  />
                  <Form.Item
                    name={['POHeader', 'approvedAmount']}
                    label={<FormattedMessage id="pages.approvedAmount" />}
                  >
                    <InputNumber disabled />
                  </Form.Item>
                  <Form.Item
                    name={['POHeader', 'totalTax']}
                    label={<FormattedMessage id="pages.tax" />}
                  >
                    <InputNumber disabled />
                  </Form.Item>
                </TabPane>
                <TabPane
                  tab={
                    <Badge count={poDtlErr}>
                      <FormattedMessage id="pages.poLine" />
                    </Badge>
                  }
                  key="2"
                >
                  <Form.Item hidden name={['PODetail', 'id']} label="ID">
                    <Input disabled />
                  </Form.Item>
                  <Form.Item hidden name={['PODetail', 'poNum']} label="ID">
                    <Input disabled />
                  </Form.Item>
                  <Form.Item
                    name={['PODetail', 'poLine']}
                    label={<FormattedMessage id="pages.poLine" />}
                  >
                    <InputNumber readOnly disabled />
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.partNum" />} required>
                    <Input.Group compact>
                      <Form.Item
                        noStyle
                        name={['PODetail', 'partNum']}
                        rules={[
                          {
                            required: true,
                            message: <FormattedMessage id="pages.partNum.required" />,
                          },
                        ]}
                      >
                        <Input style={{ width: 120 }} disabled />
                      </Form.Item>
                      <Form.Item noStyle>
                        <QuerySelect
                          width={680}
                          sysReportName="PartSearch"
                          text={<FormattedMessage id="pages.select" />}
                          title={<FormattedMessage id="pages.partNum" />}
                          btntype="primary"
                          setCurrent={setCurrent}
                          scroll={{ x: 'max-content', y: '200px' }}
                          params={{ InActive: 'false' }}
                        />
                      </Form.Item>
                      <Form.Item name={['PODetail', 'revisionNum']} noStyle>
                        {selectRev}
                      </Form.Item>
                      <Form.Item name={['PODetail', 'ium']} noStyle>
                        <Input style={{ width: 60 }} placeholder="IUM" disabled />
                      </Form.Item>
                      <Form.Item noStyle>
                        <Button
                          type="default"
                          icon={<BulbOutlined />}
                          onClick={() => setVisible3(true)}
                        />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    name={['PODetail', 'lineDesc']}
                    label={<FormattedMessage id="pages.partDescription" />}
                  >
                    <Input.TextArea readOnly disabled />
                  </Form.Item>
                  <Form.Item
                    name={['PODetail', 'unitCost']}
                    label={<FormattedMessage id="pages.taxUnitCost" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.taxUnitCost.required" />,
                      },
                    ]}
                  >
                    <Input prefix="￥" style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item name={['PODetail', 'tax']} label={<FormattedMessage id="tax" />}>
                    <Input prefix="￥" style={{ width: 200 }} disabled />
                  </Form.Item>

                  <Form.Item
                    label={<FormattedMessage id="pages.orderQty" />}
                    name={['PODetail', 'orderQty']}
                    hidden
                  >
                    <InputNumber min={0} />
                  </Form.Item>
                  <Form.Item
                    name={['PODetail', 'miscCost']}
                    label={<FormattedMessage id="pages.miscCost" />}
                  >
                    <InputNumber />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
                    <Input.Group compact>
                      <Form.Item name={['PODetail', 'taxable']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.taxable" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['PODetail', 'openLine']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.openline" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </TabPane>
                <TabPane
                  tab={
                    <Badge count={poRelErr}>
                      <FormattedMessage id="pages.poRel" />
                    </Badge>
                  }
                  key="3"
                >
                  <Form.Item hidden name={['PORel', 'id']}>
                    <Input />
                  </Form.Item>
                  <Form.Item hidden name={['PORel', 'poNum']}>
                    <Input />
                  </Form.Item>
                  <Form.Item hidden name={['PORel', 'poLine']}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.poRelNum" />}
                    style={{ marginBottom: 0 }}
                  >
                    <Input.Group compact>
                      <Form.Item name={['PORel', 'poRelNum']}>
                        <InputNumber disabled />
                      </Form.Item>
                      <Form.Item name={['PORel', 'openRelease']} valuePropName="checked">
                        <Checkbox style={{ marginLeft: 10 }}>
                          <FormattedMessage id="pages.openline" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>

                  <Form.Item
                    name={['PORel', 'promiseDt']}
                    label={<FormattedMessage id="pages.promiseDate" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.promiseDate.required" />,
                      },
                    ]}
                  >
                    <DatePicker />
                  </Form.Item>
                  <Form.Item
                    name={['PORel', 'dueDate']}
                    label={<FormattedMessage id="pages.dueDate" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.dueDate.required" /> },
                    ]}
                  >
                    <DatePicker />
                  </Form.Item>
                  <Form.Item
                    name={['PORel', 'tranType']}
                    label={<FormattedMessage id="pages.poType" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.poType.required" /> },
                    ]}
                  >
                    <Radio.Group
                      name="radiogroup"
                      onChange={(e: any) => setTranType(e.target.value)}
                    >
                      <Radio value="PUR_STK">
                        <FormattedMessage id="pages.PUR_STK" />
                      </Radio>
                      <Radio value="PUR_MTL">
                        <FormattedMessage id="pages.PUR_MTL" />
                      </Radio>
                      <Radio value="PUR_SUB">
                        <FormattedMessage id="pages.PUR_SUB" />
                      </Radio>
                      <Radio value="PUR_SO">
                        <FormattedMessage id="pages.PUR_SO" />
                      </Radio>
                      <Radio value="PUR_UKN">
                        <FormattedMessage id="pages.PUR_UKN" />
                      </Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.relaJob" />}
                    hidden={!(tranType == 'PUR_MTL' || tranType == 'PUR_SUB')}
                  >
                    <Input.Group compact>
                      <Form.Item name={['PORel', 'jobNum']} noStyle>
                        <Input
                          style={{ width: 100 }}
                          placeholder={intl.formatMessage({ id: 'pages.jobNum' })}
                        />
                      </Form.Item>
                      <Form.Item name={['PORel', 'assemblySeq']} noStyle>
                        <InputNumber placeholder={intl.formatMessage({ id: 'pages.assemblySeq' })}/>
                      </Form.Item>
                      <Form.Item name={['PORel', 'jobSeq']} noStyle>
                        <InputNumber placeholder={intl.formatMessage({ id: 'pages.jobSeq' })}/>
                      </Form.Item>
                      <Form.Item noStyle hidden={tranType != 'PUR_MTL'}>
                        <QuerySelect
                          width={780}
                          sysReportName="JobMtlSearch"
                          text={<FormattedMessage id="pages.select" />}
                          title={<FormattedMessage id="pages.jobMtl" />}
                          btntype="primary"
                          setCurrent={setPORelJob}
                          scroll={{ x: 'max-content', y: '200px' }}
                          params={{
                            JobReleased: 'true',
                            SubContract: 'false',
                          }}
                        />
                      </Form.Item>
                      <Form.Item noStyle hidden={tranType != 'PUR_SUB'}>
                        <QuerySelect
                          width={780}
                          sysReportName="JobOprSearch"
                          text={<FormattedMessage id="pages.select" />}
                          title={<FormattedMessage id="pages.jobMtl" />}
                          btntype="primary"
                          setCurrent={setPORelJobOpr}
                          scroll={{ x: 'max-content', y: '200px' }}
                          params={{
                            JobReleased: 'true',
                            SubContract: 'true',
                          }}
                        />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.saleOrder" />}
                    hidden={tranType != 'PUR_SO'}
                  >
                    <Input.Group compact>
                      <Form.Item name={['PORel', 'orderNum']} noStyle>
                        <Input style={{ width: 100 }} />
                      </Form.Item>
                      <Form.Item name={['PORel', 'orderLine']} noStyle>
                        <InputNumber />
                      </Form.Item>
                      <Form.Item name={['PORel', 'orderRelNum']} noStyle>
                        <InputNumber />
                      </Form.Item>
                      <Form.Item noStyle>
                        <QuerySelect
                          width={780}
                          sysReportName="SoSearch"
                          text={<FormattedMessage id="pages.select" />}
                          title={<FormattedMessage id="pages.orderNum" />}
                          btntype="primary"
                          setCurrent={setOrderRelJob}
                          scroll={{ x: 'max-content', y: '200px' }}
                        />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.reqNum" />}
                    hidden={tranType != 'PUR_STK'}
                  >
                    <Input.Group compact>
                      <Form.Item name={['PORel', 'reqNum']} noStyle>
                        <Input style={{ width: 100 }} />
                      </Form.Item>
                      <Form.Item noStyle>
                        <QuerySelect
                          width={780}
                          sysReportName="DemandSearch"
                          text={<FormattedMessage id="pages.select" />}
                          title={<FormattedMessage id="pages.jobMtl" />}
                          btntype="primary"
                          setCurrent={setPORelDemd}
                          scroll={{ x: 'max-content', y: '200px' }}
                        />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.relQty" />}
                    name={['PORel', 'relQty']}
                    rules={[{ required: true, message: <FormattedMessage id="pages.relQty.required" /> }]}
                  >
                    <InputNumber min={0} />
                  </Form.Item>

                  <Form.Item
                    label={<FormattedMessage id="pages.commentText" />}
                    name={['PORel', 'commentText']}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.GLAccount" />}>
                    <Input.Group compact>
                      <Form.Item name={['PORel', 'GLAccount']}>
                        <Input style={{ width: 100 }} />
                      </Form.Item>
                      <Form.Item name={['PORel', 'GLAccountDesc']}>
                        <Input style={{ width: 120 }} placeholder={intl.formatMessage({id:'pages.GLAccountDesc'})} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </TabPane>
              </Tabs>
            </Card>
          </Col>
          <Col xs={24} sm={24} md={24} lg={12} xl={12}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Card
                  title={<FormattedMessage id="pages.poLine" />}
                  extra={[
                    <Space key="S1">
                      <Button
                        type="dashed"
                        icon={<PlusOutlined />}
                        onClick={newPODetail}
                        disabled={disabled}
                      >
                        <span>
                          <FormattedMessage id="pages.add" />
                        </span>
                      </Button>
                      <Button
                        danger
                        type="primary"
                        icon={<CloseOutlined />}
                        onClick={delBatchD}
                        disabled={disabled}
                      >
                        <span>
                          <FormattedMessage id="pages.delete" />
                        </span>
                      </Button>
                    </Space>,
                  ]}
                >
                  <Table
                    rowKey="id"
                    size="small"
                    columns={columns}
                    loading={loading}
                    dataSource={dataSource}
                    rowSelection={rowSelection}
                    onRow={(record) => {
                      return {
                        onClick: () => {
                          setPODetail(record);
                        },
                      };
                    }}
                  />
                </Card>
              </Col>
              <Col span={24}>
                <Card
                  title={<FormattedMessage id="pages.poRelNum" />}
                  extra={[
                    <Space key="S2">
                      <Button
                        type="dashed"
                        icon={<PlusOutlined />}
                        onClick={newPORel}
                        disabled={disabled}
                      >
                        <span>
                          <FormattedMessage id="pages.add" />
                        </span>
                      </Button>
                      <Button
                        danger
                        type="primary"
                        icon={<CloseOutlined />}
                        onClick={delBatchR}
                        disabled={disabled}
                      >
                        <span>
                          <FormattedMessage id="pages.delete" />
                        </span>
                      </Button>
                    </Space>,
                  ]}
                >
                  <Table
                    rowKey="id"
                    size="small"
                    columns={columnRel}
                    loading={loading}
                    dataSource={dataSource2}
                    rowSelection={rowSelection2}
                    onRow={(record) => {
                      return {
                        onClick: () => {
                          setPORel(record);
                        },
                      };
                    }}
                  />
                </Card>
              </Col>
            </Row>
          </Col>
        </Row>
      </Form>

      <Modal
        width={1024}
        title={<FormattedMessage id="pages.poPrint" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => setVisible(false)}
        footer={false}
      >
        <PrintModal>
          <TempletePO data={data} configData={props.currentConfig} vendor={vendor} terms={terms} />
        </PrintModal>
      </Modal>
      <Drawer
        title={<FormattedMessage id="pages.poSuggest" />}
        placement="right"
        closable={true}
        visible={visible3}
        onClose={() => setVisible3(false)}
        getContainer={false}
        mask={true}
        maskClosable={true}
        destroyOnClose
        width="70%"
      >
        <SuggComp partNum={partNum} />
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
  currentConfig: user.currentConfig,
}))(ViewPage);
